package com.project.nhantvt.MBean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.project.entity.Enquiry;
import com.project.nhantvt.SessionBean.EnquiryBeanRemote;

@ManagedBean(name="mEnquiry")
@SessionScoped
public class MEnquiry implements Serializable {

	private static final long serialVersionUID = 1L;
	
	private Enquiry enq;
	
	private boolean submit = false;
	
	private ArrayList<Enquiry> allEnquiry;
	
	private int currentEnq;
	
	public MEnquiry() {
		enq = new Enquiry();
	}

	public Enquiry getEnq() {
		return enq;
	}

	public void setEnq(Enquiry enq) {
		this.enq = enq;
	}

	public boolean isSubmit() {
		return submit;
	}

	public void setSubmit(boolean submit) {
		this.submit = submit;
	}

	public ArrayList<Enquiry> getAllEnquiry() throws NamingException {
		Context ctx = new InitialContext();
		EnquiryBeanRemote beanRemote = (EnquiryBeanRemote) ctx
				.lookup("MySweetHome/EnquiryBean/remote");
		allEnquiry = (ArrayList<Enquiry>)beanRemote.GetAllEnquiry();
		
		if (allEnquiry.size() != 0) {
			return allEnquiry;
		}
		else {
			return null;
		}
	}

	public int getCurrentEnq() {
		return currentEnq;
	}

	public void setCurrentEnq(int currentEnq) {
		this.currentEnq = currentEnq;
	}
	
	public void remove() throws NamingException {
		Context ctx = new InitialContext();
		EnquiryBeanRemote beanRemote = (EnquiryBeanRemote) ctx
				.lookup("MySweetHome/EnquiryBean/remote");
		System.out.println(currentEnq);
		FacesContext context = FacesContext.getCurrentInstance();
		
		boolean result = beanRemote.remove(currentEnq);
		
		if (result) 
			context.addMessage(null, new FacesMessage(
					FacesMessage.SEVERITY_INFO, "Successful",
					"Delete Sucessful!"));
		else 
			context.addMessage(null, new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "Error", "Delete failed"));
	}
	
	public String CreateNewEnquiry() throws NamingException
	{
		Context ctx = new InitialContext();
		EnquiryBeanRemote enqRe = (EnquiryBeanRemote)ctx.lookup("MySweetHome/EnquiryBean/remote");
		enq.setCreationDate(new java.sql.Date(new Date().getTime()));
		enq.setSubject("There is message sent from "+enq.getEmail());
		if(enqRe.createEnquiry(enq))
		{
			this.submit = true;
			return "Success";
			
		} else
		{
			this.submit = false;
			return "Failed";
		}
	}
}
